import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, Pressable, RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Stack, useRouter } from 'expo-router';

import { useAuth } from '@/context/auth-context';
import { apiRequest } from '@/utils/api';
import { PageHeader } from '@/components/page-header';
import { CircleThumbnail } from '@/components/circle-thumbnail';
import { mapProductToThumbnail, ProductThumbnail } from '@/utils/product-thumb';

const palette = {
  background: '#fdf7fb',
  surface: '#ffffff',
  accent: '#ff8fb1',
  border: 'rgba(214, 106, 138, 0.18)',
  textPrimary: '#2f1f2b',
  textMuted: '#78657a',
  textHint: '#9c8aa0',
};

type ApiProduct = {
  id: number;
  title?: string | null;
  price?: number | null;
  updated_at?: string | null;
  cover_asset?: any;
  images?: any[];
};

type PurchasedItem = {
  id: number;
  title: string;
  price: number | null;
  purchasedAt: string;
  imageUrl: string | null;
};

export default function PurchasesScreen() {
  const router = useRouter();
  const { user, token } = useAuth();
  const [items, setItems] = useState<PurchasedItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchPurchases = useCallback(
    async (refresh = false) => {
      if (!user || !token) return;
      if (refresh) {
        setRefreshing(true);
      } else {
        setLoading(true);
      }
      try {
        const ids = await apiRequest<number[]>('/purchases', { token });
        const uniqueIds = Array.from(
          new Set((ids || []).map((n) => Number(n)).filter((n) => Number.isFinite(n) && n > 0)),
        );

        const details = await Promise.all(
          uniqueIds.map(async (id) => {
            try {
              const product = await apiRequest<ApiProduct>(`/products/${id}`);
              const thumb: ProductThumbnail = mapProductToThumbnail(product);
              return {
                id: thumb.id,
                title: thumb.title,
                price: thumb.price,
                purchasedAt: product.updated_at || new Date().toISOString(),
                imageUrl: thumb.imageUrl,
              } as PurchasedItem;
            } catch {
              return {
                id,
                title: `商品 #${id}`,
                price: null,
                purchasedAt: new Date().toISOString(),
                imageUrl: null,
              };
            }
          }),
        );
        setItems(details);
        setError(null);
      } catch (e) {
        setError(e instanceof Error ? e.message : '加载已购商品失败，请稍后重试');
      } finally {
        if (refresh) {
          setRefreshing(false);
        } else {
          setLoading(false);
        }
      }
    },
    [token, user],
  );

  useEffect(() => {
    fetchPurchases(false);
  }, [fetchPurchases]);

  const formatCurrency = (value: number | null) =>
    typeof value === 'number' ? `¥${value.toFixed(2)}` : '¥--';

  const formatDate = (value: string) => {
    const d = new Date(value);
    return Number.isNaN(d.getTime())
      ? value
      : d.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
        });
  };

  return (
    <SafeAreaView style={styles.safeArea}>
      <Stack.Screen options={{ title: '已购商品' }} />
      <PageHeader title="已购商品" />
      <ScrollView
        contentContainerStyle={styles.container}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => fetchPurchases(true)} />}
      >
        <View style={styles.card}>
          {loading ? (
            <View style={styles.stateBox}>
              <ActivityIndicator />
              <Text style={styles.stateText}>正在加载已购商品，请稍候…</Text>
            </View>
          ) : error ? (
            <View style={styles.stateBox}>
              <Text style={[styles.stateText, styles.stateTextDanger]}>{error}</Text>
            </View>
          ) : items.length === 0 ? (
            <View style={styles.stateBox}>
              <Text style={styles.stateText}>暂时还没有已购记录</Text>
            </View>
          ) : (
            items.map((it) => (
              <Pressable
                key={it.id}
                style={styles.row}
                onPress={() => router.push({ pathname: '/c/product/[id]', params: { id: String(it.id) } })}
              >
                <CircleThumbnail uri={it.imageUrl} size={56} />
                <View style={styles.rowContent}>
                  <Text style={styles.title}>{it.title}</Text>
                  <Text style={styles.meta}>购买时间：{formatDate(it.purchasedAt)}</Text>
                </View>
                <Text style={styles.price}>{formatCurrency(it.price)}</Text>
              </Pressable>
            ))
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: palette.background },
  container: { padding: 16, gap: 16 },
  card: {
    borderRadius: 24,
    backgroundColor: palette.surface,
    padding: 12,
    borderWidth: 1,
    borderColor: palette.border,
    gap: 12,
  },
  stateBox: {
    paddingVertical: 24,
    alignItems: 'center',
    gap: 8,
  },
  stateText: { fontSize: 12, color: palette.textHint },
  stateTextDanger: { color: '#d64f7c' },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 14,
    paddingVertical: 14,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#eee',
  },
  rowContent: {
    flex: 1,
  },
  title: { fontSize: 15, fontWeight: '600', color: palette.textPrimary },
  meta: { marginTop: 4, fontSize: 12, color: palette.textHint },
  price: { fontSize: 14, fontWeight: '700', color: palette.textPrimary },
});
